package org.tinygame.herostory;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author anan
 * @create 2022-05-01 8:22
 */
public class GameMsgDecoder extends ChannelInboundHandlerAdapter{

    static final private Logger LOGGER = LoggerFactory.getLogger(GameMsgDecoder.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        if(null == ctx || null == msg) return;

        if(!(msg instanceof BinaryWebSocketFrame)){
            return;
        }
        try {
            BinaryWebSocketFrame frame = (BinaryWebSocketFrame) msg;
            ByteBuf byteBuf = frame.content();

            byteBuf.readShort();
            int msgCode = byteBuf.readShort();

            byte[] msgBody = new byte[byteBuf.readableBytes()];
            byteBuf.readBytes(msgBody);

            Message.Builder msgBuilder = GameMsgRecognizer.getBuilderByMsgCode(msgCode);
            msgBuilder.clear();
            msgBuilder.mergeFrom(msgBody);

            Message cmd = msgBuilder.build();
            if(null != cmd){
                 ctx.fireChannelRead(cmd);
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
    }
}
